/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月28日
 */
package com.massyframework.beanskin.launcher.deploying;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.ModuleIdentifier;
import com.massyframework.beanskin.ModuleJarsLocator;
import com.massyframework.beanskin.SimpleModuleIdentifier;
import com.massyframework.beanskin.launcher.scanning.ModuleResources;
import com.massyframework.beanskin.launcher.scanning.ModuleResourcesUtils;
import com.massyframework.beanskin.util.localstore.LocalStore;
import com.massyframework.beanskin.util.version.Version;

/**
 * 运行框架部署器
 * @author huangkh
 *
 */
public class FrameworkDeployer {

	private Logger logger = LoggerFactory.getLogger(FrameworkDeployer.class);
	private LocalStore localStore;
	
	/**
	 * 构造器
	 * @param localStore {@link LocalStore}
	 */
	public FrameworkDeployer(LocalStore localStore) {
		this.localStore = Objects.requireNonNull(localStore, "\"localStore\" cannot be null.");
	}

	/**
	 * 部署
	 * @param debug {@link boolean},是否运行在调试模式下
	 * @param deployModules {@link Set}, 重新部署的模块
	 * @param {@link ModuleJarsLocator}
	 */
	public ModuleJarsLocator deployAndLocate(boolean debug, Set<ModuleIdentifier> deployModules) {
		ModuleJarsLocator result = debug ?
				new DebugModelModuleURLLocator(localStore) : 
					new DefaultModuleURLLocator(localStore);
		Path outputDir = localStore.getDeploymentDirectory(null);
		List<ModuleResources> resources = 
				ModuleResourcesUtils.scanning(this.getClass().getClassLoader());
		
		for (ModuleResources resource: resources) {	
			boolean deployed = false;
			for (Map.Entry<String, URL> entry: resource.getResources().entrySet()) {
				Path outputFile = outputDir.resolve(entry.getKey());
				if (!Files.exists(outputFile, new LinkOption[]{ LinkOption.NOFOLLOW_LINKS})) {
					deployed = true;
					try {
						if (!Files.exists(outputFile.getParent())) {
							Files.createDirectories(outputFile.getParent());
						}
						Files.createFile(outputFile);
						Files.copy(entry.getValue().openStream(), outputFile, StandardCopyOption.REPLACE_EXISTING);;
					}catch(IOException e) {
						if (logger.isErrorEnabled()) {
							logger.error(e.getMessage(), e);
						}
					}
				}
			}
			
			ModuleIdentifier module = null;
			if (deployed) {
				module = SimpleModuleIdentifier.newBuilder()
					.groupId(resource.getGroupId())
					.moduleId(resource.getModuleId())
					.version(Version.parseVersion(resource.getVersion()))
					.build();
				deployModules.add(module);
			}
			
			if (debug) {
				if (resource.getPomFile() != null) {
					if (module == null) {
						module =
							SimpleModuleIdentifier.newBuilder()
								.groupId(resource.getGroupId())
								.moduleId(resource.getModuleId())
								.version(Version.parseVersion(resource.getVersion()))
								.build();
					}
					((DebugModelModuleURLLocator)result).addModuleResources(module, resource);
				}
			}
		}
		
		return result;
	}
}
